import { useEffect, useState } from 'react';
import lazyload from './utils/lazyload';
export type IRoute = {
  name: string;
  key: string;
  path?: string;
  // 当前页是否展示面包屑
  breadcrumb?: boolean;
  children?: IRoute[];
  // 当前路由是否渲染菜单项，为 true 的话不会在菜单中显示，但可通过路由地址访问。
  ignore?: boolean;
  // 是否为大权限
  code?: string[] | null; //去权限码
  component?: any;
  ignoreRoute?: boolean;
};

export const routes: IRoute[] = [
  {
    name: 'menu.dashboard',
    key: 'Dashboard',
    code: ['dashboard/stat'],
    component: lazyload(() => import(`./pages/dashboard`)),
  },

  {
    name: 'menu.myTasks',
    key: 'MyTasks',
    code: ['violation/tasks'],
    children: [
      {
        name: 'enu.myTasks',
        key: 'MyTasks/List',
        breadcrumb: false,
        component: lazyload(() => import(`./pages/myTasks`)),
        ignore: true,
        ignoreRoute: true,
      },
      {
        name: 'enu.myTasks',
        key: 'MyTasks/Detail',
        breadcrumb: false,
        component: lazyload(() => import(`./pages/violation/details`)),
        ignore: true,
        ignoreRoute: true,
      },
    ],
  },

  {
    name: 'menu.violation',
    key: 'Violation',
    code: ['violation/search'],
    children: [
      {
        name: 'menu.violation.list',
        key: 'Violation/List',
        code: ['violation/search'],
        breadcrumb: false,
        component: lazyload(() => import(`./pages/violation/list`)),
        ignore: true,
      },
      {
        name: 'menu.violation.details',
        key: 'Violation/Detail',
        component: lazyload(() => import(`./pages/violation/details`)),
        code: ['violation/get'],
        breadcrumb: false,
        ignore: true,
      },
      {
        name: 'menu.violation.create',
        key: 'Violation/Create',
        component: lazyload(() => import(`./pages/violation/create`)),
        breadcrumb: false,
        ignore: true,
        ignoreRoute: true,
      },
    ],
  },
  {
    name: 'menu.entities',
    key: 'Entities',
    code: ['entity/search'],
    component: lazyload(() => import(`./pages/entities`)),
  },
  {
    name: 'menu.entityProfiles',
    key: 'ComplaintOfficer',
    code: ['compliance/search'],
    component: lazyload(() => import(`./pages/entityProfiles`)),
  },
  {
    name: 'menu.authentication',
    key: 'Authentication',
    code: ['auth/role/current'],
    component: lazyload(() => import(`./pages/authentication`)),
  },
  {
    name: 'menu.otprequest',
    key: 'OTPRequest',
    code: ['otp/search'],
    component: lazyload(() => import(`./pages/otprequest`)),
  },
  {
    name: 'menu.deviceManager',
    key: 'DeviceManager',
    code: ['device/search'],
    component: lazyload(() => import(`./pages/deviceManager`)),
  },
];

export const getName = (path: string, routes) => {
  return routes.find((item) => {
    const itemPath = `/${item.key}`;
    if (path === itemPath) {
      return item.name;
    } else if (item.children) {
      return getName(path, item.children);
    }
  });
};

/**
 * 根据用户权限过滤路由
 * @returns [IRoute[], string] 返回过滤后的路由和默认路由
 */
const useRoute = (meuns): [IRoute[], string] => {
  function hasPermission(code: any, route: any) {
    if (route.code) {
      return code.some((a: any) => route.code.includes(a));
    } else {
      return true;
    }
  }
  /**
   * 递归过滤路由
   * @param routes 路由数组
   * @param arr 过滤后的路由数组
   * @returns IRoute[] 返回过滤后的路由数组
   */
  const filterRoute = (routes: IRoute[], arr = []): IRoute[] => {
    // 如果路由数组为空，直接返回空数组
    if (!routes.length) {
      return [];
    }
    // 遍历路由数组
    for (const route of routes) {
      // 有子路由不判断权限，直接下一步
      const { ignoreRoute } = route;
      const visible = hasPermission(meuns, route) || ignoreRoute;
      if (visible) {
        if (route.children && route.children.length) {
          // 创建一个新的路由，清空子路由
          const newRoute = { ...route, children: [] };
          // 递归过滤子路由
          filterRoute(route.children, newRoute.children);
          // 如果子路由不为空，将新路由添加到过滤后的路由数组中
          if (newRoute.children.length > 0) {
            arr.push(newRoute);
          }
        } else {
          arr.push({ ...route });
        }
      }
    }

    return arr;
  };

  // 初始化过滤后的路由数组
  const [permissionRoute, setPermissionRoute] = useState(routes);
  const [defaultRoute, setDefaultRoute] = useState('');
  // 使用Effect钩子来过滤路由
  useEffect(() => {
    // 过滤路由
    const newRoutes = filterRoute(routes);
    // 更新过滤后的路由数组
    setPermissionRoute(newRoutes);
    // 获取过滤后的路由数组的第一个路由
    const first = newRoutes[0];
    if (first) {
      // 获取第一个路由的子路由的第一个路由的 key，如果不存在则获取第一个路由的 key
      const firstRoute = first?.children?.[0]?.key || first.key;
      setDefaultRoute(firstRoute);
    }
    // 因为依赖于用户权限，所以不需要额外的依赖项
  }, [JSON.stringify(meuns)]);
  // 返回过滤后的路由数组和默认路由
  return [permissionRoute, defaultRoute];
};

export default useRoute;
